package cn.shyouchi.wuguanjia.android.ui.event.proprietor;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.View;
import android.widget.Button;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.event.EventApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.DataChangeEvent;
import cn.shyouchi.wuguanjia.android.impl.ModuleItemClickListener;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.model.OwnerEntity;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class PreviewProprietorActivity extends BaseActivity implements ModuleItemClickListener<ProprietorInfoModel> {


    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.rv_proprietor_info)
    RecyclerView mRvProprietorInfo;
    @BindView(R.id.advance_edit_dialog_cancel_button)
    Button mAdvanceEditDialogCancelButton;
    @BindView(R.id.advance_edit_dialog_confirm_button)
    Button mAdvanceEditDialogConfirmButton;
    List<ProprietorInfoModel> mModels = new ArrayList<>();

    ProprietorInfoAdapter mAdapter;

    OwnerEntity.ProprietorBean proprietor;
    private final String BASE_URL = "http://118.178.88.132:8000";

    String projectId;

    boolean loaded = false;


    @Override
    public int initContentView() {
        return R.layout.activity_preview_proprietor;
    }

    @Override
    public void initInjector() {
        projectId = getIntent().getStringExtra("projectId");
        proprietor = getIntent().getParcelableExtra("proprietor");
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        mTopBar.setTitle(getTitle().toString());
        setSupportActionBar(mTopBar.getToolbar());
        initModel();
        if (proprietor != null) {
            mAdapter = new ProprietorInfoAdapter(mModels, this);
            mRvProprietorInfo.setAdapter(mAdapter);
            mRvProprietorInfo.setLayoutManager(new LinearLayoutManager(mContext));
        } else {
            ToastUtil.showToast("数据无效");
        }

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @OnClick({R.id.advance_edit_dialog_cancel_button, R.id.advance_edit_dialog_confirm_button})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.advance_edit_dialog_cancel_button:
                EventApi eventApi = new EventApi(mContext);
                eventApi.delOwner(String.valueOf(proprietor.getId()))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                            @Override
                            public void onNext(BaseRequestResult result) {
                                EventBus.getDefault().post(new DataChangeEvent());
                                finish();
                            }
                        });

//                startActivityForResult(new Intent(mContext, AddProprietorActivity.class), REQUEST_TYPE_ADD_PROPRIETOR)
                break;
            case R.id.advance_edit_dialog_confirm_button:
                if (loaded) {
                    Intent intent = new Intent(mContext, AddProprietorActivity.class);
                    intent.putExtra("projectId", projectId);
                    intent.putExtra("proprietor", proprietor);
                    startActivity(intent);
                    finish();
                } else {
                    ToastUtil.showToast("数据加载中，请稍后...");
                }
                break;
        }
    }

    private void initModel() {
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_AVATAR, "头像", "请输入业主头像", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, false));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_NAME, "姓名", "请输入业主姓名", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true, proprietor.getName()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_GENDER, "性别", ProprietorInfoModel.EDIT_TYPE_SEL, new String[]{"男", "女"}, true, proprietor.getInfo().getSex()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_AGE, "年龄", "请输入业主年龄", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_NUMBER, false, true, String.valueOf(proprietor.getInfo().getAge())));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_HEIGHT, "身高", "请输入业主身高", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_NUMBER, false, true, String.valueOf(proprietor.getInfo().getHeight())));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_DUTY, "职务", "请输入业主职务", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true, proprietor.getInfo().getJob()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_WORK_TIME, "工作时间", "如：09:00-17:00", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true, proprietor.getInfo().getWorkinghours()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_PLATE, "车牌号", "如：沪A88888", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true, proprietor.getInfo().getNumberplates()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_PHONE, "手机号", "请输入业主手机号", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_NUMBER, false, true, String.valueOf(proprietor.getInfo().getPhone())));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_OTHER, "其他", "请输入其他信息", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, true, false, proprietor.getInfo().getRemarks()));
        getImgPath(BASE_URL + proprietor.getImages());
    }


    private void getImgPath(String url) {
        Observable.just(url)
                .subscribeOn(Schedulers.io())
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        FutureTarget<File> future = Glide
                                .with(mContext)
                                .load(s).downloadOnly(500, 500);
                        try {
                            File file = future.get();
                            String path = file.getAbsolutePath();
                            return path;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                        throw new RuntimeException("图片地址无效");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        mModels.get(0).setValue(proprietor.getImages());
                        mAdapter.notifyDataSetChanged();
                        loaded = true;
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(String s) {
                        proprietor.setImages(s);
                    }
                });
    }


    @Override
    public void moduleItemClick(ProprietorInfoModel model) {
        if (model.getType() == ProprietorInfoModel.INFO_TYPE_AVATAR) {
            ArrayList<String> models = new ArrayList<>();
            models.add(model.getValue());
            startActivity(BGAPhotoPickerPreviewActivity.newIntent(this,1, models, models, 0, false));

        }
    }

    @Override
    public void moduleItemLongClick(ProprietorInfoModel model) {

    }

    @Override
    public void onDel(ProprietorInfoModel model) {

    }
}
